#pragma once

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include<unistd.h>
#include "Log.hpp"

#define BACKLOG 5
class TcpServer
{
private:
    int port_;
    int listen_sock_;
    static TcpServer *svr;
    TcpServer(int port)
        : port_(port), listen_sock_(-1)
    {}
    TcpServer(const TcpServer &) {}

public:
    static TcpServer *getinstance(int port)
    {
        static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
        if (svr == nullptr)
        {
            pthread_mutex_lock(&lock);
            if (svr == nullptr)
            {
                svr = new TcpServer(port);
                svr->InitServer();
            }
            pthread_mutex_unlock(&lock);
        }
        return svr;
    }
    void InitServer()
    {
        Socket();
        Bind();
        Listen();
        // LOG(INFO,"tcp_server init success!");
    }
    void Socket()
    {
        listen_sock_ = socket(AF_INET, SOCK_STREAM, 0);
        if (listen_sock_ < 0)
        {
            LOG(FATAL,"liten socket error");
            exit(1);
        }
        int opt = 1;
        setsockopt(listen_sock_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        // LOG(INFO,"create listen socket ... success");
    }

    void Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(listen_sock_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL,"bind error");
            exit(2);
        }
        // LOG(INFO,"bind socket ... success");
    }
    void Listen()
    {
        if (listen(listen_sock_, BACKLOG) < 0)
        {
            LOG(FATAL,"liten socket error");
            exit(3);
        }
        // LOG(INFO,"listen socket ... success");
    }
    int Sock()
    {
        return listen_sock_;
    }
    ~TcpServer()
    {
        if(listen_sock_>=0)
            close(listen_sock_);
    }
};

TcpServer *TcpServer::svr = nullptr;